package com.yezao.baseui.sequenceableDialog

import android.app.Dialog
import android.content.DialogInterface
import android.util.Log
import androidx.collection.ArraySet
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import java.util.*
import java.util.concurrent.LinkedBlockingDeque

class SequenceDialogManager(private val mLifecycleOwner: LifecycleOwner) : LifecycleEventObserver {
    private val mCurrentDialog: SequenceDialog? = null
    override fun onStateChanged(
        source: LifecycleOwner,
        event: Lifecycle.Event
    ) {
        when (event) {
            Lifecycle.Event.ON_PAUSE -> {
            }
            Lifecycle.Event.ON_RESUME -> {
                if (mCurrentDialog!!.state == 1) {
                    return
                }
                if (hasNext()) {
                    popNext()
                }
            }
            Lifecycle.Event.ON_DESTROY -> for (sequenceDialog in mDialogQueue) {
                sequenceDialog.target.dismiss()
            }
        }
    }

    private class SequenceDialog(
        var target: Dialog,
        //优先级
        var level: Int,
        var mManager: SequenceDialogManager
    ) : DialogInterface.OnDismissListener {
        var state = 0 //状态   0队列中  1显示中  -1 dismissed
        private val mDismissListeners: MutableSet<DialogInterface.OnDismissListener> =
            ArraySet()

        fun addDimissListener(listener: DialogInterface.OnDismissListener?) {
            if (listener == null) {
                return
            }
            mDismissListeners.add(listener)
        }

        fun onShow() {
            Log.i(TAG, "onShow: ")
            target.show()
            state = 1
        }

        fun remove() {
            target.setOnDismissListener(null)
            target.dismiss()
        }

        override fun onDismiss(dialog: DialogInterface) {
            state = -1
            for (dismissListener in mDismissListeners) {
                dismissListener.onDismiss(dialog)
            }
            if (mManager.hasNext()) {
                mManager.popNext()
            }
        }

        init {
            target.setOnDismissListener(this)
        }
    }

    private val mDialogQueue: Queue<SequenceDialog> =
        LinkedBlockingDeque()

    fun add(dialog: Dialog, level: Int = 0, dismissListener: DialogInterface.OnDismissListener? = null) {
        val sequenceDialog = SequenceDialog(dialog, level, this)
        sequenceDialog.addDimissListener(dismissListener)
        mDialogQueue.add(sequenceDialog)
    }

    operator fun hasNext(): Boolean {
        return !mDialogQueue.isEmpty()
    }

    fun popNext() {
        if (mLifecycleOwner.lifecycle.currentState != Lifecycle.State.RESUMED) {
            return
        }
        val poll = mDialogQueue.poll()
        poll.onShow()
    }

    companion object {
        private const val TAG = "SequenceDialogManager"
    }

}